<template>
  <div class="stat-container">
    <!-- 时间筛选 -->
    <div class="filter-bar">
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="YYYY-MM-DD"
        @change="loadChartData"
      />
    </div>

    <!-- 图表容器 -->
    <div ref="chartEl" style="width: 100%; height: 600px;"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'

const dateRange = ref<string[]>([])
const chartEl = ref<HTMLElement>()
const token = localStorage.getItem('token');
let chart: echarts.ECharts

interface StatData {
  date: string
  loginCount: number
  registerCount: number
  foundCount: number
  lostCount: number
}

// 初始化图表
const initChart = () => {
  chart = echarts.init(chartEl.value!)
  
  const option: echarts.EChartsOption = {
    title: { text: '系统数据统计', left: 'center' },
    tooltip: { trigger: 'axis' },
    legend: { 
      data: ['登录人数', '注册人数', '招领发布', '失物发布'],
      top: 30
    },
    xAxis: {
      type: 'category',
      data: [] // 动态填充
    },
    yAxis: { type: 'value' },
    dataZoom: [{
      type: 'slider',
      show: true,
      start: 0,
      end: 100
    }],
    series: [
      { name: '登录人数', type: 'line', smooth: true },
      { name: '注册人数', type: 'line', smooth: true },
      { name: '招领发布', type: 'bar' },
      { name: '失物发布', type: 'bar' }
    ]
  }

  chart.setOption(option)
}

// 加载数据
const loadChartData = async () => {
  try {
    const params = {
      startDate: dateRange.value?.[0],
      endDate: dateRange.value?.[1]
    }

    const { data } = await axios.get<StatData[]>('/stat/daily', { params, headers: { Authorization: `Bearer ${token}` } })
    
    const option: echarts.EChartsOption = {
      xAxis: { data: data.map(item => item.date) },
      series: [
        { data: data.map(item => item.loginCount) },
        { data: data.map(item => item.registerCount) },
        { data: data.map(item => item.foundCount) },
        { data: data.map(item => item.lostCount) }
      ]
    }

    chart.setOption(option)
  } catch (error) {
    console.error('加载统计数据失败', error)
  }
}

// 初始化
onMounted(() => {
  initChart()
  loadChartData()
})

// 响应式调整
window.addEventListener('resize', () => chart.resize())
</script>

<style scoped>
.stat-container {
  padding: 20px;
  background: #fff;
}

.filter-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 20px;
}
</style>